//
//  BCSColor.swift
//  BCFoundation
//
//  Created by chun.chen on 2021/8/16.
//  UIColor 扩展

import Foundation

extension UIColor {
    
    public convenience init(rgb: UInt) {
        let r = CGFloat((rgb >> 16) & 0xFF)
        let g = CGFloat((rgb >> 8) & 0xFF)
        let b = CGFloat(rgb & 0xFF)
        self.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: 1.0)
    }

    public convenience init(rgbStr: String) {
        var cString: String = rgbStr.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()

        if cString.hasPrefix("#") {
            cString.remove(at: cString.startIndex)
        }
        // 默认返回black
        if cString.count != 6 {
            self.init(red: 0, green: 0, blue: 0, alpha: 1.0)
        }

        var rgbValue: UInt64 = 0
        Scanner(string: cString).scanHexInt64(&rgbValue)

        let red = CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0
        let green = CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0
        let blue = CGFloat(rgbValue & 0x0000FF) / 255.0
        self.init(red: red, green: green, blue: blue, alpha: 1.0)
    }
}
